import { defineStore } from 'pinia'
import { ref } from 'vue'
import { SongListService } from '@/apis/music'

export const useAllMusicStore = defineStore(
    'all-music',
    () => {
        const musicList = ref<song_info[]>([])
        const links = ref<SongLinks>({
            first: null,
            last: null,
            next: null,
            prev: null
        })
        const meta = ref<SongListMeta>({
            current_pate: 0,
            from: 0,
            path: "",
            per_page: 0,
            to: 0
        })
        const songs_params = ref<songs_params>({
            page: 1,
            sort: "title" ,
            order: 'asc'
        })
        const setMusicList = (newOverView : SongsResult) => {
            musicList.value = newOverView.data
            links.value = newOverView.links
            meta.value = newOverView.meta
        }

        const AddMusicList = (newOverView : SongsResult) => {
            musicList.value = [...musicList.value, ...newOverView.data ]
            links.value = newOverView.links
            meta.value = newOverView.meta
        }

        const initFirstData = async (params:songs_params ) => {
            songs_params.value = params
            const res = await SongListService(params)
            setMusicList(res.data as SongsResult)
        }

        const getNextData = async (songs_params:songs_params) => {
            const res = await SongListService(songs_params)
            AddMusicList(res.data as SongsResult)
        }

        const MoreData = () => {
            if(links.value.next)
            {
                const nextParams = songs_params.value
                nextParams.page = nextParams.page + 1
                getNextData(nextParams)
            }
        }

        const setLike = (songId: string,liked: boolean) => {
            //播放列表
            const tmpList = musicList.value
            tmpList.map(item => {
                if(item.id === songId)
                {
                    item.liked = liked
                }

            })
            musicList.value = tmpList
        }

        return {
            musicList,
            links,
            meta,
            MoreData,
            initFirstData,
            getNextData,
            AddMusicList,
            setLike
        }
    },
    {
        persist: false
    }
)
